package sk.naive.talker.persistence;

import sk.naive.talker.util.PropertyConfiguration;
import sk.naive.talker.server.DbLayer;
import sk.naive.talker.props.*;

import java.util.*;

/**
 * PersistentPropertyStoreImpl.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.3 $ $Date: 2007-05-07 10:34:20 $
 */
public final class PersistentPropertyStoreImpl {
	private Integer id;
	private PropertyStoreImpl store;

	public PersistentPropertyStoreImpl(Integer id, PropertyConfiguration propertyConfiguration) {
		store = new PropertyStoreImpl(propertyConfiguration);
		this.id = id;
	}

	public void setNonpersistent(String property, Object value)
		throws PropertyStoreException
	{
		store.set(property, value);
	}

	public void set(String property, Object value)
		throws PropertyStoreException
	{
		store.set(property, value);
		if (getPersistent().contains(property)) {
			try {
				String storedValue = null;
				if (value != null) {
					Property propertyObject = getProperty(property);
					storedValue = propertyObject.toString(value);
				}
				new DbLayer().storeProperty(getId(), property, storedValue);
			} catch (PersistenceException e) {
				throw new PropertyStoreException(e);
			}
		}
	}

	public void setStoredValue(String key, String value) throws PropertyStoreException {
		Object objValue = value;
		Property propertyObject = getProperty(key);
		if (propertyObject != null) {
			objValue = propertyObject.toObject(value);
		}
		store.set(key, objValue);
	}

	public Object get(String key) {
		return store.get(key);
	}

	public Integer getId() {
		return id;
	}

	public Property getProperty(String key) {
		return store.getProperty(key);
	}

	public Set<String> getSettable() {
		return store.getSettable();
	}

	public Set<String> getPersistent() {
		return store.getPersistent();
	}

	public Set<String> getGlobal() {
		return store.getGlobal();
	}

	public Map<String,Object> getProperties() {
		return store.getProperties();
	}

	public PropertyConfiguration getPropertyConfiguration() {
		return store.getPropertyConfiguration();
	}
}
